//ShopCar模块下的vuex
import {
  DeleteShopCarGoodsById,
  GetShopCarList,
  PostEditShopCarGoodsIsChecked,
} from "@/api";

const state = {
  //存储数据
  shopCarList: [],
};

const mutations = {
  //唯一修改state中的数据，方法名大写
  SHOPCARLIST(state, shopCarList) {
    state.shopCarList = shopCarList;
  },
};

const actions = {
  //方法的中转，然后调用mutations中的方法
  async getShopCarList({ commit }) {
    let result = await GetShopCarList();
    if (result.code == 200) {
      commit("SHOPCARLIST", result.data);
    }
  },
  //删除购物车中的商品
  async deleteShopCarGoodsById({ commit }, skuId) {
    let result = await DeleteShopCarGoodsById(skuId);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject("Failed");
    }
  },
  // 更新购物车中商品的选中状态
  async postEditShopCarGoodsIsChecked({ commit }, { skuId, isChecked }) {
    let result = await PostEditShopCarGoodsIsChecked(skuId, isChecked);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject("Failed");
    }
  },
  // 更新所有的商品的选中状态
  postAllGoodsIsChecked({ dispatch, getters }, checked) {
    let promiseAll = [];
    getters.cartInfoList.forEach((item) => {
      if (item.isChecked != checked) {
        let mypromise = dispatch("postEditShopCarGoodsIsChecked", {
          skuId: item.skuId,
          isChecked: checked,
        });
        promiseAll.push(mypromise);
      }
    });
    return Promise.all(promiseAll);
  },
};

const getters = {
  //相当于计算属性
  cartInfoList(state) {
    if (state.shopCarList.length <= 0) return [];
    return state.shopCarList[0].cartInfoList || [];
  },
};

export default { state, mutations, actions, getters };
